import { createStore } from "vuex";
import { getToken, setToken } from "@/utils/auth";
import { login, get_userinfo } from "@/api/index";
import { LoginType } from "@/utils/@type";
export default createStore({
  state: {
    token: getToken(),
    userInfo: null
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token;
      setToken(token);
    },
    SET_INFO: (state, info) => {
      state.userInfo = info;
    }
  },
  actions: {
    getInfo({ commit }) {
      return new Promise((resolve, reject) => {
        get_userinfo()
          .then((res) => {
            commit("SET_INFO", res.data);
            resolve("");
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
    login({ commit }, data: LoginType) {
      return new Promise((resolve, reject) => {
        login(data)
          .then((res) => {
            commit("SET_TOKEN", res.data.token);
            resolve("");
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
    logout({ commit }) {
      return new Promise((resolve, reject) => {
        commit("SET_TOKEN", "");
        commit("SET_INFO", "");
        resolve("");
      });
    }
  },
  modules: {}
});
